<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>排球颠球计数系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f0f0;
            display: flex;
            min-height: 100;
        }
        .main-container {
            display: flex;
            width: 100%;
            height: 100%;
            padding: 20px;
            gap: 20px;
        }
        .left-section {
            flex: 0.5;
            background-color: white;
            padding: 20px 0 0 0;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
        }
        .middle-section {
            flex: 0.3;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .right-section {
            flex: 0.2;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .right-block {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .video-block {
            width: 600px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        #videoElement {
            width: 600px;
            height: 600px;
            object-fit: contain;
            border-radius: 4px;
            background-color: #000;
            position: relative;
        }
        .timer-block {
            width: 600px;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .timer-display {
            width: 100%;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
        }
        .controls {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 20px;
        }
        .controls button {
            width: 100%;
            margin: 0;
        }
        button {
            padding: 10px 20px;
            background-color: #4096ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        button:hover {
            background-color: #4096ff;
            box-shadow: 0 2px 6px rgba(5, 145, 255, 0.4);
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
            box-shadow: none;
        }
        #status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            background-color: #f8f9fa;
        }
        h1 {
            margin: 0 0 20px 0;
            color: #333;
        }
        h2 {
            margin: 0 0 15px 0;
            color: #444;
            font-size: 1.2em;
        }
        .video-source-form {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .video-source-form select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            width: 100%;
        }
        .video-source-form input[type="text"] {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            width: 100%;
        }
        .video-source-form .source-info {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
            font-size: 14px;
        }
        .video-source-form .source-info p {
            margin: 5px 0;
        }
        .student-info-form {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .student-info-form input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            width: 100%;
        }
        .student-info-form select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            width: 100%;
            height: 38px; /* 与输入框高度一致 */
        }
        .student-info-form button {
            width: 100%;
            margin-top: 10px;
        }
        .detection-settings {
            position: fixed;
            top: 100px;
            right: 20px;
            background: rgba(255, 255, 255, 0.9);
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: none;
            z-index: 1000;
            width: 600px;
            cursor: move;
        }
        .detection-settings.active {
            display: block;
        }
        .detection-settings h3 {
            margin: 0 0 15px 0;
            color: #333;
            cursor: move;
            user-select: none;
        }
        .detection-settings .settings-container {
            display: flex;
            gap: 20px;
        }
        .detection-settings .column {
            flex: 1;
        }
        .detection-settings .setting-group {
            margin-bottom: 15px;
        }
        .detection-settings label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }
        .detection-settings input[type="range"] {
            width: 100%;
            margin: 5px 0;
        }
        .detection-settings .value-display {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
        }
        .detection-box {
            position: absolute;
            border: 2px solid #4096ff;
            pointer-events: none;
            display: none;
            top: 0;
            left: 0;
        }
        .detection-box.active {
            display: block;
        }
        .query-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 9999;
        }
        .query-content {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: white;
            padding: 20px;
            display: flex;
            flex-direction: column;
            z-index: 10000;
        }
        .query-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #dee2e6;
            padding-right: 30px;
        }
        .query-table-container {
            flex: 1;
            overflow-y: auto;
            padding-right: 30px;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <div class="left-section">
            <div class="video-block">
                <video id="videoElement" autoplay playsinline></video>
            </div>
            <div class="timer-block">
                <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
                    <h2 style="margin: 0;">计时</h2>
                    <div class="timer-display" id="timerDisplay" style="background-color: #f8f9fa; padding: 15px; border-radius: 4px; text-align: center; margin: 0; flex: 1; margin-left: 20px;">
                        <span style="font-size: 36px; font-weight: bold; color: #333;">00:00:00</span>
                        <p style="margin: 10px 0 0 0; color: #666;">当前计时</p>
                    </div>
                </div>
            </div>
            <div class="detection-box" id="detectionBox"></div>
            <div class="detection-box" id="groundDetectionBox" style="border-color: #FFA500;"></div>
            <div class="detection-settings" id="detectionSettings">
                <h3>系统设置</h3>
                <div class="settings-container">
                    <div class="column">
                        <div class="setting-group">
                            <label>判球上限 (px)</label>
                            <input type="range" id="topValue" min="0" max="600" value="0">
                            <div class="value-display">当前值: <span id="topDisplay">0</span>px</div>
                        </div>
                        <div class="setting-group">
                            <label>判球左限 (px)</label>
                            <input type="range" id="leftValue" min="0" max="600" value="0">
                            <div class="value-display">当前值: <span id="leftDisplay">0</span>px</div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="setting-group">
                            <label>判球下限 (px)</label>
                            <input type="range" id="bottomValue" min="0" max="600" value="0">
                            <div class="value-display">当前值: <span id="bottomDisplay">0</span>px</div>
                        </div>
                        <div class="setting-group">
                            <label>判球右限 (px)</label>
                            <input type="range" id="rightValue" min="0" max="600" value="0">
                            <div class="value-display">当前值: <span id="rightDisplay">0</span>px</div>
                        </div>
                    </div>
                </div>
                <h3 style="margin-top: 20px;">地面设置</h3>
                <div class="settings-container">
                    <div class="column">
                        <div class="setting-group">
                            <label>上边距 (px)</label>
                            <input type="range" id="groundTopValue" min="0" max="600" value="580">
                            <div class="value-display">当前值: <span id="groundTopDisplay">580</span>px</div>
                        </div>
                        <div class="setting-group">
                            <label>左边距 (px)</label>
                            <input type="range" id="groundLeftValue" min="0" max="600" value="0">
                            <div class="value-display">当前值: <span id="groundLeftDisplay">0</span>px</div>
                        </div>
                    </div>
                    <div class="column">
                        <div class="setting-group">
                            <label>下边距 (px)</label>
                            <input type="range" id="groundBottomValue" min="0" max="600" value="0">
                            <div class="value-display">当前值: <span id="groundBottomDisplay">0</span>px</div>
                        </div>
                        <div class="setting-group">
                            <label>右边距 (px)</label>
                            <input type="range" id="groundRightValue" min="0" max="600" value="0">
                            <div class="value-display">当前值: <span id="groundRightDisplay">0</span>px</div>
                        </div>
                    </div>
                </div>
                <button id="applyDetectionSettings">保存设置</button>
            </div>
            <div id="status"></div>
        </div>
        <div class="middle-section">
            <div class="right-block">
                <h1>排球垫球专用系统</h1>
                <div class="student-info-form" id="studentInfoForm">
                    <select id="studentGender" required>
                        <option value="">请选择性别</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                    <input type="text" id="studentName" placeholder="请输入姓名" required>
                    <input type="text" id="studentId" placeholder="请输入学号" required>
                    <button id="submitStudentInfo">提交信息</button>
                </div>
                <div id="studentInfoDisplay" style="margin-top: 10px; padding: 10px; background-color: #f8f9fa; border-radius: 4px; display: none;">
                    <p>学生：<span id="currentStudentName"></span></p>
                    <p>学号：<span id="currentStudentId"></span></p>
                    <p>性别：<span id="currentStudentGender"></span></p>
                </div>
                <div style="margin-top: 15px; padding: 15px; background-color: #e8f5e9; border-radius: 4px; text-align: center;">
                    <h3 style="margin: 0 0 10px 0; color: #2e7d32;">最终成绩</h3>
                    <span id="finalScore" style="font-size: 36px; font-weight: bold; color: #2e7d32;">0</span>
                </div>
            </div>
            <div class="right-block">
                <div style="display: flex; align-items: center; justify-content: space-between; margin: 10px;">
                    <h2 style="margin: 0;">计数</h2>
                    <div class="count-display" style="background-color: #f8f9fa; padding: 15px; border-radius: 4px; text-align: center; margin: 0; flex: 1; margin-left: 20px;">
                        <span id="countOutput" style="font-size: 36px; font-weight: bold; color: #333;">0</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="right-section">
            <div class="right-block">
                <div style="display: flex; gap: 10px;">
                    <button id="queryButton" style="flex: 1;">记录查询</button>
                    <button id="detectionButton" style="flex: 1;">系统设置</button>
                </div>
                <div class="number-pad" style="margin-top: 15px; background-color: #f8f9fa; border-radius: 4px; padding: 15px;">
                    <input type="text" id="numberInput" style="width: 100%; padding: 10px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 18px; text-align: center;" readonly>
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px;">
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">1</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">2</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">3</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">4</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">5</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">6</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">7</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">8</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">9</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">←</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">0</button>
                        <button class="num-btn" style="padding: 15px; font-size: 18px;">↵</button>
                    </div>
                </div>
                <div class="controls">
                    <button id="startButton" style="display: none;">开始测试</button>
                    <button id="stopButton" style="display: none;">停止测试</button>
                    <button id="foulButton" style="display: none;">范规/减数</button>
                    <button id="saveButton" style="display: none;">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查询结果遮罩层 -->
    <div class="query-overlay" id="queryOverlay">
        <div class="query-content">
            <div class="query-header">
                <h2 style="margin: 0;">测试记录查询</h2>
                <button id="backButton" style="padding: 8px 16px; font-size: 14px;">返回测试界面</button>
            </div>
            <div id="recordTable" class="query-table-container">
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="background-color: #e9ecef;">
                            <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6; font-size: 16px; width: 80px;">序号</th>
                            <th style="padding: 12px; text-align: left; border-bottom: 1px solid #dee2e6; font-size: 16px;">测试记录</th>
                        </tr>
                    </thead>
                    <tbody id="recordList">
                        <!-- 测试记录将通过JavaScript动态添加 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        const video = document.getElementById('videoElement');
        const timerDisplay = document.getElementById('timerDisplay');
        const startButton = document.getElementById('startButton');
        const stopButton = document.getElementById('stopButton');
        const detectionButton = document.getElementById('detectionButton');
        const detectionSettings = document.getElementById('detectionSettings');
        const detectionBox = document.getElementById('detectionBox');
        const heightRange = document.getElementById('heightRange');
        const widthRange = document.getElementById('widthRange');
        const verticalPosition = document.getElementById('verticalPosition');
        const horizontalPosition = document.getElementById('horizontalPosition');
        const heightValue = document.getElementById('heightValue');
        const widthValue = document.getElementById('widthValue');
        const verticalValue = document.getElementById('verticalValue');
        const horizontalValue = document.getElementById('horizontalValue');
        const applyDetectionSettings = document.getElementById('applyDetectionSettings');
        const status = document.getElementById('status');
        const studentInfoForm = document.getElementById('studentInfoForm');
        const studentInfoDisplay = document.getElementById('studentInfoDisplay');
        const currentStudentName = document.getElementById('currentStudentName');
        const currentStudentId = document.getElementById('currentStudentId');
        const currentStudentGender = document.getElementById('currentStudentGender');
        let stream = null;
        let mediaRecorder = null;
        let recordedChunks = [];
        let isRecording = false;
        let startTime = null;
        let timerInterval = null;
        let count = 0;
        let isCounting = false;
        let lastCountTime = null;
        let countHistory = [];
        let isPaused = false;
        let pauseStartTime = null;
        let totalPausedTime = 0;
        let ws = null;
        let isTimerRunning = false;

        // 定义学生信息对象
        let studentInfo = {
            name: '',
            student_id: '',
            gender: '',
            score: 0
        };

        // 页面加载完成后不自动启动摄像头
        document.addEventListener('DOMContentLoaded', () => {
            startButton.style.display = 'none';
            stopButton.style.display = 'none';
            resetTimer();
        });

        // 请求摄像头权限并显示视频
        async function startCamera() {
            try {
                // 设置权限为仅本次允许
                const constraints = {
                    video: {
                        width: { ideal: 1280 },
                        height: { ideal: 720 },
                        facingMode: "user",
                        permissions: {
                            video: {
                                permission: "prompt",
                                prompt: "仅这次访问时允许"
                            }
                        }
                    }
                };
                
                stream = await navigator.mediaDevices.getUserMedia(constraints);
                video.srcObject = stream;
                startButton.style.display = 'none';
                stopButton.style.display = 'inline-block';
                status.textContent = '摄像头已启动';
                
                // 获取视频信息
                const track = stream.getVideoTracks()[0];
                const settings = track.getSettings();
            } catch (err) {
                status.textContent = '无法访问摄像头: ' + err.message;
                startButton.style.display = 'inline-block';
                stopButton.style.display = 'none';
            }
        }

        // 开始录制
        function startRecording() {
            // 如果已经在录制，则先停止
            if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                mediaRecorder.stop();
            }

            recordedChunks = [];
            
            // 检查支持的 MIME 类型
            const mimeType = MediaRecorder.isTypeSupported('video/mp4;codecs=h264,aac') 
                ? 'video/mp4;codecs=h264,aac'
                : 'video/webm;codecs=vp8,opus';
            
            mediaRecorder = new MediaRecorder(stream, {
                mimeType: mimeType
            });

            mediaRecorder.ondataavailable = async (event) => {
                if (event.data.size > 0) {
                    recordedChunks.push(event.data);
                }
            };

            // 每秒产生一个数据块
            mediaRecorder.start(1000);
            status.textContent = '正在录制和上传...';
        }

        // 停止录制和上传
        async function stopRecording() {
            if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                mediaRecorder.stop();
            }

            stopCamera();
        }

        // 停止摄像头
        function stopCamera() {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
                video.srcObject = null;
                startButton.style.display = 'inline-block';
                stopButton.style.display = 'none';
            }
        }

        // 检查权限状态
        async function checkPermissionStatus() {
            try {
                const result = await navigator.permissions.query({ name: 'camera' });
                result.onchange = () => {
                    if (result.state === 'granted') {
                        status.textContent = '';
                    } else if (result.state === 'denied') {
                        status.textContent = '摄像头权限被拒绝，请在浏览器设置中更改权限';
                    } else if (result.state === 'prompt') {
                        status.textContent = '请允许访问摄像头';
                    }
                };
            } catch (err) {
                console.log('权限状态检查失败:', err);
            }
        }

        // 数字键盘功能
        const numberInput = document.getElementById('numberInput');
        const numButtons = document.querySelectorAll('.num-btn');
        let isSearching = false;

        numButtons.forEach(button => {
            button.addEventListener('click', () => {
                const value = button.textContent;
                if (value === '←') {
                    // 删除最后一个字符
                    numberInput.value = numberInput.value.slice(0, -1);
                } else if (value === '↵') {
                    // 当输入完成时，触发查询
                    if (numberInput.value) {
                        searchStudentInfo(numberInput.value);
                    }
                } else {
                    // 添加数字
                    numberInput.value += value;
                }
            });
        });

        // 查询学生信息
        function searchStudentInfo(studentId) {
            if (isSearching) return;
            isSearching = true;

            fetch(`/api/student_info/${studentId}`)
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => {
                            throw new Error(err.error || '查询失败');
                        });
                    }
                    return response.json();
                })
                .then(student => {
                    // 更新学生信息对象
                    studentInfo.name = student.name;
                    studentInfo.student_id = student.student_id;
                    studentInfo.gender = student.gender;
                    studentInfo.score = 0; // 重置得分
                    
                    // 更新显示信息
                    currentStudentName.textContent = student.name;
                    currentStudentId.textContent = student.student_id;
                    currentStudentGender.textContent = student.gender;
                    studentInfoForm.style.display = 'none';
                    studentInfoDisplay.style.display = 'block';
                    // 显示开始测试按钮
                    startButton.style.display = 'inline-block';
                    // 清空输入框
                    numberInput.value = '';
                })
                .catch(error => {
                    console.error('查询失败:', error);
                    alert(error.message || '查询失败，请稍后重试');
                })
                .finally(() => {
                    isSearching = false;
                });
        }

        // 修改提交学生信息按钮事件
        document.getElementById('submitStudentInfo').addEventListener('click', function() {
            const name = document.getElementById('studentName').value;
            const studentId = document.getElementById('studentId').value;
            const gender = document.getElementById('studentGender').value;

            // 验证必填字段
            if (!name || !studentId || !gender) {
                alert('请填写所有必填信息');
                return;
            }

            // 准备提交数据
            const data = {
                name: name,
                student_id: studentId,
                gender: gender
            };

            // 发送POST请求到后端
            fetch('/api/student_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.error || '提交失败');
                    });
                }
                return response.json();
            })
            .then(result => {
                // 更新学生信息对象
                studentInfo.name = name;
                studentInfo.student_id = studentId;
                studentInfo.gender = gender;
                studentInfo.score = 0; // 重置得分
                
                // 更新显示信息
                currentStudentName.textContent = name;
                currentStudentId.textContent = studentId;
                currentStudentGender.textContent = gender;
                studentInfoForm.style.display = 'none';
                studentInfoDisplay.style.display = 'block';
                // 显示开始测试按钮
                startButton.style.display = 'inline-block';
                alert('学生信息添加成功！');
                // 清空表单
                document.getElementById('studentName').value = '';
                document.getElementById('studentId').value = '';
                document.getElementById('studentGender').value = '';
            })
            .catch(error => {
                console.error('提交失败:', error);
                alert(error.message || '提交失败，请稍后重试');
            });
        });

        // 页面加载时检查权限状态
        checkPermissionStatus();

        // 更新计时器显示
        function updateTimer() {
            if (isTimerRunning) {
                const currentTime = new Date().getTime();
                const elapsedTime = currentTime - startTime;
                const minutes = Math.floor(elapsedTime / 60000);
                const seconds = Math.floor((elapsedTime % 60000) / 1000);
                timerDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

                // 如果计时到1分钟，停止计时
                if (minutes >= 1) {
                    stopTimer();
                }
            }
        }

        // 开始计时
        function startTimer() {
            if (!isTimerRunning) {
                startTime = new Date().getTime();
                isTimerRunning = true;
                timerInterval = setInterval(updateTimer, 1000);
            }
        }

        // 停止计时
        function stopTimer() {
            if (isTimerRunning) {
                isTimerRunning = false;
                clearInterval(timerInterval);
                // 更新最终得分
                document.getElementById('finalScore').textContent = countOutput.textContent;
                studentInfo.score = countOutput.textContent;
                // 调用服务端接口禁用计数
                fetch('/api/disable_counter', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(studentInfo)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('禁用计数失败');
                    }
                })
                .catch(error => {
                    console.error('禁用计数失败:', error);
                    status.textContent = '禁用计数失败，请刷新页面重试';
                });
                // 隐藏停止测试按钮
                stopButton.style.display = 'none';
            }
        }

        // 重置计时器
        function resetTimer() {
            stopTimer();
            timerDisplay.textContent = '00:00:00';
        }

        // 修改开始测试按钮事件
        startButton.addEventListener('click', () => {
            // 生成文件名（使用时间戳）
            const timestamp = new Date().getTime();
            // 保存文件名到学生信息对象
            studentInfo.video_filename = timestamp;
            
            // 显示检测区域并设置颜色
            const detectionBox = document.getElementById('detectionBox');
            detectionBox.style.display = 'block';
            detectionBox.style.borderColor = studentInfo.gender === '男' ? '#0000FF' : '#FF0000';
            
            // 设置视频源为服务端摄像头
            video.src = `/api/camera/${timestamp}`;
            video.play();
            
            // 建立WebSocket连接
            if (ws) {
                ws.close();
            }
            ws = new WebSocket('ws://localhost:5000/ws');
            
            // 连接建立时的处理
            ws.onopen = () => {
                console.log('WebSocket连接已建立');
                status.textContent = '已连接到服务器';
                
                // 发送开始检测消息
                ws.send(JSON.stringify({
                    type: 'start_check',
                    filename: timestamp
                }));
            };

            // 接收消息的处理
            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                if (data.type === 'counter_update') {
                    // 更新计数值
                    countOutput.textContent = data.count;
                } else if (data.type === 'detection') {
                    // 显示识别框
                    const canvas = document.createElement('canvas');
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;
                    const ctx = canvas.getContext('2d');
                    
                    // 根据性别设置识别框颜色
                    const boxColor = studentInfo.gender === '男' ? '#0000FF' : '#FF0000';
                    
                    // 绘制识别框
                    ctx.strokeStyle = boxColor;
                    ctx.lineWidth = 2;
                    ctx.strokeRect(data.x, data.y, data.width, data.height);
                    
                    // 将canvas叠加到视频上
                    const overlay = document.createElement('div');
                    overlay.style.position = 'absolute';
                    overlay.style.top = '0';
                    overlay.style.left = '0';
                    overlay.style.width = '100%';
                    overlay.style.height = '100%';
                    overlay.style.pointerEvents = 'none';
                    overlay.appendChild(canvas);
                    
                    // 移除旧的识别框
                    const oldOverlay = video.parentElement.querySelector('.detection-overlay');
                    if (oldOverlay) {
                        oldOverlay.remove();
                    }
                    
                    // 添加新的识别框
                    overlay.className = 'detection-overlay';
                    video.parentElement.appendChild(overlay);
                } else if (data.type === 'error') {
                    status.textContent = data.message;
                    console.error('WebSocket错误:', data.message);
                }
            };

            // 连接关闭时的处理
            ws.onclose = () => {
                console.log('WebSocket连接已断开');
                status.textContent = '与服务器断开连接';
                stopTimer();
                // 隐藏检测区域
                detectionBox.style.display = 'none';
            };

            // 连接错误时的处理
            ws.onerror = (error) => {
                console.error('WebSocket错误:', error);
                status.textContent = '连接出错，请刷新页面重试';
                stopTimer();
                // 隐藏检测区域
                detectionBox.style.display = 'none';
            };
            
            startTimer();
            startButton.style.display = 'none';
            stopButton.style.display = 'inline-block';
            foulButton.style.display = 'inline-block';
            saveButton.style.display = 'inline-block';
        });

        // 修改停止测试按钮事件
        stopButton.addEventListener('click', () => {
            stopRecording();
            stopTimer();
            // 隐藏检测区域
            document.getElementById('detectionBox').style.display = 'none';
            startButton.style.display = 'inline-block';
            stopButton.style.display = 'none';
            foulButton.style.display = 'none';
            saveButton.style.display = 'none';
        });

        // 检测区域设置相关函数
        function updateDetectionBox() {
            // 更新人体检测区域
            const top = parseInt(document.getElementById('topValue').value);
            const bottom = parseInt(document.getElementById('bottomValue').value);
            const left = parseInt(document.getElementById('leftValue').value);
            const right = parseInt(document.getElementById('rightValue').value);
            
            // 计算人体检测框的位置和大小
            const height = 600 - top - bottom;
            const width = 600 - left - right;
            
            // 更新人体检测框样式
            detectionBox.style.height = `${height}px`;
            detectionBox.style.width = `${width}px`;
            detectionBox.style.top = `${top}px`;
            detectionBox.style.left = `${left}px`;
            
            // 更新人体检测区域显示值
            document.getElementById('topDisplay').textContent = top;
            document.getElementById('bottomDisplay').textContent = bottom;
            document.getElementById('leftDisplay').textContent = left;
            document.getElementById('rightDisplay').textContent = right;

            // 更新地面检测区域
            const groundTop = parseInt(document.getElementById('groundTopValue').value);
            const groundBottom = parseInt(document.getElementById('groundBottomValue').value);
            const groundLeft = parseInt(document.getElementById('groundLeftValue').value);
            const groundRight = parseInt(document.getElementById('groundRightValue').value);
            
            // 计算地面检测框的位置和大小
            const groundHeight = 600 - groundTop - groundBottom;
            const groundWidth = 600 - groundLeft - groundRight;
            
            // 更新地面检测框样式
            const groundDetectionBox = document.getElementById('groundDetectionBox');
            groundDetectionBox.style.height = `${groundHeight}px`;
            groundDetectionBox.style.width = `${groundWidth}px`;
            groundDetectionBox.style.top = `${groundTop}px`;
            groundDetectionBox.style.left = `${groundLeft}px`;
            
            // 更新地面检测区域显示值
            document.getElementById('groundTopDisplay').textContent = groundTop;
            document.getElementById('groundBottomDisplay').textContent = groundBottom;
            document.getElementById('groundLeftDisplay').textContent = groundLeft;
            document.getElementById('groundRightDisplay').textContent = groundRight;
        }

        // 添加拖动功能
        let isDragging = false;
        let currentX;
        let currentY;
        let initialX;
        let initialY;
        let xOffset = 0;
        let yOffset = 0;

        function dragStart(e) {
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON') {
                return;
            }
            
            initialX = e.clientX - xOffset;
            initialY = e.clientY - yOffset;

            if (e.target === detectionSettings || e.target.tagName === 'H3') {
                isDragging = true;
            }
        }

        function dragEnd() {
            initialX = currentX;
            initialY = currentY;
            isDragging = false;
        }

        function drag(e) {
            if (isDragging) {
                e.preventDefault();
                currentX = e.clientX - initialX;
                currentY = e.clientY - initialY;

                xOffset = currentX;
                yOffset = currentY;

                setTranslate(currentX, currentY, detectionSettings);
            }
        }

        function setTranslate(xPos, yPos, el) {
            el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
        }

        // 检测按钮点击事件
        detectionButton.addEventListener('click', () => {
            detectionSettings.classList.toggle('active');
            detectionBox.classList.toggle('active');
            document.getElementById('groundDetectionBox').classList.toggle('active');
            if (detectionSettings.classList.contains('active')) {
                updateDetectionBox();
                // 重置位置
                xOffset = 0;
                yOffset = 0;
                setTranslate(0, 0, detectionSettings);
            }
        });

        // 添加拖动事件监听器
        detectionSettings.addEventListener('mousedown', dragStart);
        document.addEventListener('mousemove', drag);
        document.addEventListener('mouseup', dragEnd);
        document.addEventListener('mouseleave', dragEnd);

        // 滑动条值变化事件
        ['topValue', 'bottomValue', 'leftValue', 'rightValue', 
         'groundTopValue', 'groundBottomValue', 'groundLeftValue', 'groundRightValue'].forEach(id => {
            document.getElementById(id).addEventListener('input', updateDetectionBox);
        });

        // 应用设置按钮点击事件
        applyDetectionSettings.addEventListener('click', () => {
            // 获取检测区域设置
            const detectionSettings = {
                top: parseInt(document.getElementById('topValue').value),
                bottom: parseInt(document.getElementById('bottomValue').value),
                left: parseInt(document.getElementById('leftValue').value),
                right: parseInt(document.getElementById('rightValue').value)
            };

            // 获取地面检测区域设置
            const groundSettings = {
                top: parseInt(document.getElementById('groundTopValue').value),
                bottom: parseInt(document.getElementById('groundBottomValue').value),
                left: parseInt(document.getElementById('groundLeftValue').value),
                right: parseInt(document.getElementById('groundRightValue').value)
            };

            // 发送设置到服务器
            fetch('/api/save_settings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    detection_area: detectionSettings,
                    ground_area: groundSettings
                })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('保存设置失败');
                }
                status.textContent = '检测区域设置已保存';
                detectionSettings.classList.remove('active');
            })
            .catch(error => {
                console.error('保存设置失败:', error);
                status.textContent = '保存设置失败，请稍后重试';
            });
        });

        // 窗口大小改变时更新检测框
        window.addEventListener('resize', updateDetectionBox);

        // 记录查询功能
        const queryButton = document.getElementById('queryButton');
        const queryOverlay = document.getElementById('queryOverlay');
        const backButton = document.getElementById('backButton');
        const recordList = document.getElementById('recordList');
        const mainContainer = document.querySelector('.main-container');

        function toggleMainInterface(show) {
            mainContainer.style.display = show ? 'flex' : 'none';
        }

        queryButton.addEventListener('click', () => {
            // 隐藏主界面
            toggleMainInterface(false);
            // 显示查询界面
            queryOverlay.style.display = 'block';
            // 加载测试记录数据
            loadTestRecords();
        });

        backButton.addEventListener('click', () => {
            // 显示主界面
            toggleMainInterface(true);
            // 隐藏查询界面
            queryOverlay.style.display = 'none';
            // 清空记录列表
            recordList.innerHTML = '';
        });

        function loadTestRecords() {
            fetch('/api/test_records')
                .then(response => response.json())
                .then(records => {
                    const tbody = document.querySelector('#recordTable tbody');
                    tbody.innerHTML = '';
                    
                    records.forEach((record, index) => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                            <td style="padding: 8px; width: 80px; text-align: center;">${index + 1}</td>
                            <td style="padding: 8px;">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <span>姓名: ${record.name}  成绩:${record.score} 个</span>
                                    <div style="display: flex; gap: 8px;">
                                        ${record.video_path ? 
                                            `<button onclick="playRecord(${record.id})" style="padding: 4px 8px; font-size: 12px; background-color: #4096ff; color: white; border: none; border-radius: 4px; cursor: pointer;">回放</button>` : 
                                            ''}
                                        <button onclick="deleteRecord(${record.id})" style="padding: 4px 8px; font-size: 12px; background-color: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">删除</button>
                                    </div>
                                </div>
                            </td>
                        `;
                        tbody.appendChild(tr);
                    });
                })
                .catch(error => {
                    console.error('获取记录失败:', error);
                    const tbody = document.querySelector('#recordTable tbody');
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="2" style="color: red; text-align: center;">
                                获取记录失败，请稍后重试
                            </td>
                        </tr>
                    `;
                });
        }

        function playRecord(recordId) {
            // 清空学生信息对象
            studentInfo.student_id = '';
            studentInfo.name = '';
            studentInfo.gender = '';
            studentInfo.score = 0;
            // 隐藏开始测试按钮
            startButton.style.display = 'none';

            fetch(`/api/test_record/${recordId}`)
                .then(response => response.json())
                .then(record => {
                    // 更新学生信息显示
                    currentStudentName.textContent = record.name;
                    currentStudentId.textContent = record.student_id;
                    currentStudentGender.textContent = record.gender;             
                    // 更新最终成绩
                    document.getElementById('finalScore').textContent = record.score;
                    
                    // 隐藏输入表单，显示信息显示区域
                    document.getElementById('studentInfoForm').style.display = 'none';
                    document.getElementById('studentInfoDisplay').style.display = 'block';
                    
                    // 设置视频源
                    if (record.video_path) {
                        video.src = `/api/test_record/${recordId}/video`;
                        video.play();

                        // 建立WebSocket连接
                        if (ws) {
                            ws.close();
                        }
                        
                        // 创建WebSocket连接
                        ws = new WebSocket('ws://localhost:5000/ws');
                        
                        // 连接建立时的处理
                        ws.onopen = () => {
                            console.log('WebSocket连接已建立');
                            status.textContent = '已连接到服务器';
                            
                            // 发送开始播放消息
                            ws.send(JSON.stringify({
                                type: 'start_playback',
                                record_id: recordId
                            }));

                            // 开始计时
                            startTimer();
                        };

                        // 接收消息的处理
                        ws.onmessage = (event) => {
                            const data = JSON.parse(event.data);
                            if (data.type === 'counter_update') {
                                // 更新计数值
                                countOutput.textContent = data.count;
                            } else if (data.type === 'detection') {
                                // 显示识别框
                                const canvas = document.createElement('canvas');
                                canvas.width = video.videoWidth;
                                canvas.height = video.videoHeight;
                                const ctx = canvas.getContext('2d');
                                
                                // 根据性别设置识别框颜色
                                const boxColor = studentInfo.gender === '男' ? '#0000FF' : '#FF0000';
                                
                                // 绘制识别框
                                ctx.strokeStyle = boxColor;
                                ctx.lineWidth = 2;
                                ctx.strokeRect(data.x, data.y, data.width, data.height);
                                
                                // 将canvas叠加到视频上
                                const overlay = document.createElement('div');
                                overlay.style.position = 'absolute';
                                overlay.style.top = '0';
                                overlay.style.left = '0';
                                overlay.style.width = '100%';
                                overlay.style.height = '100%';
                                overlay.style.pointerEvents = 'none';
                                overlay.appendChild(canvas);
                                
                                // 移除旧的识别框
                                const oldOverlay = video.parentElement.querySelector('.detection-overlay');
                                if (oldOverlay) {
                                    oldOverlay.remove();
                                }
                                
                                // 添加新的识别框
                                overlay.className = 'detection-overlay';
                                video.parentElement.appendChild(overlay);
                            } else if (data.type === 'error') {
                                status.textContent = data.message;
                                console.error('WebSocket错误:', data.message);
                            }
                        };

                        // 连接关闭时的处理
                        ws.onclose = () => {
                            console.log('WebSocket连接已断开');
                            status.textContent = '与服务器断开连接';
                            stopTimer();
                        };

                        // 连接错误时的处理
                        ws.onerror = (error) => {
                            console.error('WebSocket错误:', error);
                            status.textContent = '连接出错，请刷新页面重试';
                            stopTimer();
                        };
                    }
                    
                    // 显示主界面，隐藏查询界面
                    toggleMainInterface(true);
                    queryOverlay.style.display = 'none';
                })
                .catch(error => {
                    console.error('获取记录失败:', error);
                    status.textContent = '获取记录失败，请稍后重试';
                });
        }

        // 添加删除记录的函数
        function deleteRecord(recordId) {
            if (confirm('确定要删除这条测试记录吗？此操作不可恢复。')) {
                fetch(`/api/test_record/${recordId}`, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除失败');
                    }
                    // 删除成功后重新加载记录列表
                    loadTestRecords();
                })
                .catch(error => {
                    console.error('删除失败:', error);
                    alert('删除失败，请稍后重试');
                });
            }
        }

        // 修改犯规/减数按钮事件
        foulButton.addEventListener('click', () => {
            const currentScore = parseInt(document.getElementById('finalScore').textContent);
            if (currentScore > 0) {
                document.getElementById('finalScore').textContent = currentScore - 1;
                studentInfo.score = currentScore - 1;
            }
        });

        // 添加保存按钮事件
        saveButton.addEventListener('click', () => {
            fetch('/api/test_records', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(studentInfo)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('保存失败');
                }
                alert('测试记录保存成功！');
                // 重置界面
                studentInfo.score = 0;
                document.getElementById('finalScore').textContent = '0';
                countOutput.textContent = '0';
                // 清空学生信息对象
                studentInfo.name = '';
                studentInfo.student_id = '';
                studentInfo.gender = '';
                // 重置学生信息显示
                currentStudentName.textContent = '';
                currentStudentId.textContent = '';
                currentStudentGender.textContent = '';
                // 显示学生信息表单，隐藏信息显示区域
                studentInfoForm.style.display = 'flex';
                studentInfoDisplay.style.display = 'none';
                // 隐藏按钮
                saveButton.style.display = 'none';
                foulButton.style.display = 'none';
                startButton.style.display = 'none';
                stopButton.style.display = 'none';
                // 重置计时器
                resetTimer();
                // 停止视频播放
                if (video.src) {
                    video.pause();
                    video.src = '';
                }
                // 关闭WebSocket连接
                if (ws) {
                    ws.close();
                    ws = null;
                }
            })
            .catch(error => {
                console.error('保存失败:', error);
                alert('保存失败，请稍后重试');
            });
        });

        // 在页面关闭时断开WebSocket连接
        window.addEventListener('beforeunload', () => {
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
            if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                mediaRecorder.stop();
            }
        });
    </script>
</body>
</html> 